package compnents

import (
	"centerServer/models"
	"encoding/json"
	"github.com/astaxie/beego/logs"
	"io/ioutil"
)

func WxCode2Session(wxCode string) (*models.RequstCode2Session, error) {
	/*
	{
	  "access_token": "ACCESS_TOKEN",
	  "expires_in": 7200,
	  "refresh_token": "REFRESH_TOKEN",
	  "openid": "OPENID",
	  "scope": "SCOPE"
	}
	*/
	// https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
	// https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
	var requestBack models.RequstCode2Session
	requestUrl := CODE2SESSION_URL + "appid=" + MACH_APPID + "&secret=" + MACH_APPSECRET + "&code=" + wxCode + "&grant_type=authorization_code"
	httpReques, errA := HttpGet(requestUrl)
	if errA != nil {
		logs.Error("WxAccessTokenCompnent err :" + errA.Error())
		return &requestBack, errA
	}
	defer httpReques.Body.Close()
	bodyByte, _ := ioutil.ReadAll(httpReques.Body)
	jErr := json.Unmarshal(bodyByte, &requestBack)
	if jErr != nil {
		logs.Error("WxCode2Session err :" + jErr.Error())
		return &requestBack, jErr
	}
	return &requestBack, nil
}

func WxCode2SessionA(wxCode string) (*models.RequstCode2Session, error) {
	/*
		{
		  "access_token": "ACCESS_TOKEN",
		  "expires_in": 7200,
		  "refresh_token": "REFRESH_TOKEN",
		  "openid": "OPENID",
		  "scope": "SCOPE"
		}
	*/
	// https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
	// https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
	var requestBack models.RequstCode2Session
	requestUrl := CODE2SESSION_URL + "appid=" + WXAPPID + "&secret=" + WXAPPSECRET + "&code=" + wxCode + "&grant_type=authorization_code"
	httpReques, errA := HttpGet(requestUrl)
	if errA != nil {
		logs.Error("WxAccessTokenCompnent err :" + errA.Error())
		return &requestBack, errA
	}
	defer httpReques.Body.Close()
	bodyByte, _ := ioutil.ReadAll(httpReques.Body)
	jErr := json.Unmarshal(bodyByte, &requestBack)
	if jErr != nil {
		logs.Error("WxCode2Session err :" + jErr.Error())
		return &requestBack, jErr
	}
	return &requestBack, nil
}
